#include "Ext/FilterQuery.h"

#include "NewsGroupTable.h"

using namespace std;

namespace TCServer
{
	namespace Store
	{
		quint64 NewsGroupTable::insert(const Type::NewsGroup &newsGroup)
		{
			FilterQuery q;
			q.prepare(R"(

			INSERT INTO `tc`.`newsgroup`
			(`name`,
			`iconUrl`)
			VALUES
			(?,
			?);

			)");
			q.addBindValue(newsGroup.name);
			q.addBindValue(newsGroup.iconUrl);

			q.exec();
            return q.lastInsertId().toULongLong();
		}

		void NewsGroupTable::update(const Type::NewsGroup &newsGroup)
		{
			FilterQuery q;
			q.prepare(R"(

			UPDATE `tc`.`newsgroup`
			SET
			`name` = ?,
			`iconUrl` = ?
			WHERE `id` = ?;

			)");
			q.addBindValue(newsGroup.name);
			q.addBindValue(newsGroup.iconUrl);
			q.addBindValue(newsGroup.id);

			return q.exec();
		}

		void NewsGroupTable::remove(quint64 id)
		{
			FilterQuery q;
			q.prepare(R"(

			DELETE FROM `tc`.`newsgroup`
			WHERE `id` = ?;

			)");
			q.addBindValue(id);

			return q.exec();
		}

		QList<TCServer::Type::NewsGroup> NewsGroupTable::queryAll()
		{
			FilterQuery q;
			q.prepare(R"(

			SELECT `newsgroup`.`id`,
				`newsgroup`.`name`,
				`newsgroup`.`iconUrl`
			FROM `tc`.`newsgroup`;

			)");
			QList<Type::NewsGroup> res;
			q.exec();
			while (q.next())
			{
				TCServer::Type::NewsGroup newsGroup;
				newsGroup.id = q.nextValue().toULongLong();
				newsGroup.name = q.nextValue().toString();
				newsGroup.iconUrl = q.nextValue().toString();
				res.append(newsGroup);
			}
			return res;
		}

	}
}
